package com.pipe.protocol.login;

import com.pipe.util.MysqlProtocolUtil;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Kiven
 */
public class OkAndEofPacket {
    private static Logger LOG = LoggerFactory.getLogger(OkAndEofPacket.class);

    /**len = 7*/
    public static int OK_PACKAGE_LENGTH = 7;
    /**len = 9*/
    public static int EOF_PACKAGE_LENGTH = 9;

    private short header;
    private long effectedRows;
    private long lastaInsertId;

    /**if capabilites CLIENT_PROTOCOL_41*/
    private byte[] statusFlags;
    private byte[] warnings;

    public OkAndEofPacket(short header) {
        this.header = header;
    }

    public OkAndEofPacket(short header, long effectedRows, long lastaInsertId, byte[] statusFlags, byte[] warnings) {
        this.header = header;
        this.effectedRows = effectedRows;
        this.lastaInsertId = lastaInsertId;
        this.statusFlags = statusFlags;
        this.warnings = warnings;
    }

    public static OkAndEofPacket shortBuild(ByteBuf byteBuf){
        short header = byteBuf.readUnsignedByte();
        return new OkAndEofPacket(header);
    }

    public static OkAndEofPacket build(ByteBuf byteBuf){
        short header = byteBuf.readUnsignedByte();

        long effectedRows = MysqlProtocolUtil.readLenencIntFromBytebuf(byteBuf);
        long lastaInsertId = MysqlProtocolUtil.readLenencIntFromBytebuf(byteBuf);

        /** Capabilities Flags默认是开启了CLIENT_PROTOCOL_41*/
        byte[] statusFlags = new byte[2];
        byteBuf.readBytes(statusFlags);
        byte[] warnings = new byte[2];
        byteBuf.readBytes(warnings);
        return new OkAndEofPacket(header, effectedRows, lastaInsertId, statusFlags, warnings);
    }

    public boolean isOkHead(){
        return header == 0x00;
    }

    public boolean isEofHead(){
        return header == 0xfe;
    }
}